<template>
  <a-select
    v-model:value="categoryParentId"
    placeholder="请选择上级分类"
    style="width: 100%"
    :filter-option="false"
    :not-found-content="categoryDownOptionsRef.fetching ? undefined : null"
    :options="categoryDownOptionsRef.data"
    :showSearch="true"
    @search="categoriesDown"
    :defaultOpen="true"
    :fieldNames="{ label: 'path', value: 'id', key: 'id' }"
    allow-clear
    @select="selectParentCategory"
  >
    <template v-if="categoryDownOptionsRef.fetching" #notFoundContent>
      <a-spin size="small" />
    </template>
  </a-select>
</template>

<script lang="ts" setup>
  import { reactive, ref } from 'vue';
  import { CategoryItem, CategorySearch } from '#/goods-manage/category-manage/category';
  import { categories } from '@/api/goods-manage/category-manage/category';

  // const props = defineProps(['disabled']);
  const categoryParentId = ref<string>('');

  let lastFetchId = 0;
  const labelOptions: CategoryItem[] = [];
  const categoryDownOptionsRef = reactive({
    data: labelOptions,
    fetching: false,
  });

  // 查询分类的下拉列表
  function categoriesDown(value: string, consumer?: Function) {
    lastFetchId += 1;
    const fetchId = lastFetchId;
    categoryDownOptionsRef.data = [];
    categoryDownOptionsRef.fetching = true;
    const categorySearch: CategorySearch = {
      categoryName: value,
      minLevel: 0,
      level: 3,
    };
    categories(categorySearch).then((body: CategoryItem[]) => {
      if (fetchId && fetchId !== lastFetchId) {
        // for fetch callback order
        return;
      }
      categoryDownOptionsRef.data.push(...body);
      categoryDownOptionsRef.fetching = false;
      if (consumer) {
        consumer();
      }
    });
  }

  const category_selected = defineEmits(['category:selected']);
  function selectParentCategory(_, option: CategoryItem) {
    category_selected('category:selected', option.id);
  }
</script>
